package midlet;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;

import ui.VadeMecumCameraCanvas;
import ui.VadeMecumList;
import util.VadeMecumConstants;

public class VadeMecumMIDlet extends MIDlet implements CommandListener {

	//initialize the player and the canvas
	public VadeMecumCameraCanvas canvas = null;
	
	//and other variables
	private Alert alert = null;
	
	private boolean error = false;	
	
	public Display display;
	
	private VadeMecumList optionsList1;
	
	private String[] options2 = {VadeMecumConstants.PHOTO, VadeMecumConstants.EXIT};
	
	public VadeMecumMIDlet () {
		this.display = Display.getDisplay(this);
		
		alert = new Alert("Message");
		
		this.optionsList1 = new VadeMecumList("VadeMecum Mobile Client", List.IMPLICIT, options2, null);		
		this.optionsList1.setCommandListener(this);
	}
	
	public Display getMainDisplay() {
		return this.display;
	}

	protected void startApp () {
		if (error) {
			return;
		}
		this.display.setCurrent(this.optionsList1);
	}
	
	protected void pauseApp () {
		//NOP
	}
	
	protected void destroyApp (boolean unconditional) {
		notifyDestroyed();
	}
	
	public void commandAction (Command c, Displayable d) {
		if (c == List.SELECT_COMMAND) {
			VadeMecumList current = (VadeMecumList) this.display.getCurrent();
			String selectedOption = current.getString(current.getSelectedIndex());			
			handleSelectedOption(selectedOption);			
		} else if (c == canvas.snapshot) {
			System.out.println("tira foto");
			canvas.takeSnapshot();			
		} else if (c == canvas.exitCommand) {
			this.display.setCurrent(this.optionsList1);
		}
	}

	private void handleSelectedOption(String selectedOption) {
		if (VadeMecumConstants.PHOTO.equals(selectedOption)) {
			System.out.println("photo");
			try{
				//now create the canvas
				canvas = new VadeMecumCameraCanvas(this, false);
				canvas.setCommandListener(this);
			} catch (Exception e) {
				error(e);
			}
			this.display.setCurrent(canvas);
		} else if (VadeMecumConstants.EXIT.equals(selectedOption)) {
			destroyApp(true);
		}
	}
	
	public void error(Exception e) {
		alert.setString(e.getMessage());
		alert.setTitle("Error");
		display.setCurrent(alert);
		e.printStackTrace();
		error = true;
	}
	
}
